﻿using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Wuther.Bussiness.Interface;
using Wuther.Entities.Models;
using Wuther.Util.DtoParameters;
using Wuther.Util.Helper;
using Wuther.Util.Models;
using Wuther.Util.PropertyMapping;

namespace Wuther.Bussiness.Service
{
    public class CalligraphyRepository: Repository<Calligraphy>, ICalligraphyRepository
    {

        private readonly DbContext _context;
        private readonly IPropertyMappingService _propertyMappingService;
        public CalligraphyRepository(DbContext context, IPropertyMappingService propertyMappingService) : base(context)
        {
            _context = context ?? throw new ArgumentNullException(nameof(context));
            _propertyMappingService = propertyMappingService ?? throw new ArgumentNullException(nameof(propertyMappingService));
        }

        public async Task<Calligraphy> GetCalligraphyAsync(int id)
        {
            var calligraphy = await _context.FindAsync<Calligraphy>(id);
            return calligraphy;
        }

        public async Task<PagedList<Calligraphy>> GetCalligraphysAsync(DtoCalligraphyParameter parameter)
        {
            IQueryable<Calligraphy> queryExpression = _context.Set<Calligraphy>();

            if (parameter.StartTime != null && parameter.EndTime != null)
            {
                queryExpression = queryExpression.Where(c => c.WriteTime >= parameter.StartTime && c.WriteTime <= parameter.EndTime);
            }
            if (!string.IsNullOrWhiteSpace(parameter.Title))
            {
                queryExpression = queryExpression.Where(c => c.Title.Contains(parameter.Title));
            }
            if (!string.IsNullOrWhiteSpace(parameter.UserAccount))
            {
                queryExpression = queryExpression.Where(c => c.UserAccount.Contains(parameter.UserAccount));
            }
            if (!string.IsNullOrWhiteSpace(parameter.UserName))
            {
                queryExpression = queryExpression.Where(c => c.UserName == parameter.UserName);
            }

            var mappingDictionary = _propertyMappingService.GetPropertyMapping<CalligraphyDto, Calligraphy>();
            queryExpression = queryExpression.ApplySort(parameter.OrderBy, mappingDictionary);
            return await PagedList<Calligraphy>.CreateAsync(queryExpression, parameter.PageNumber, parameter.PageSize);
        }
    }
}
